<?php 
//all the class/function includes are managed in the includer file
include("include/includer.php");

//get all the configuration variables (custom function in newzbook.php include)
getConfigVars(true);  

//if the form was just posted back, let's use the form variables - otherwise the ones above will be used
if(isset($_GET['q'])){
    $q = str_replace(' ','+',$_GET['q']);
}
if(isset($_GET['action'])){
    $action = $_GET['action'];
}
if(isset($_POST['enablehistorydisp'])){
    $config_enablehistorydisp = $_POST['enablehistorydisp'];
}
if(isset($_POST['enablepostprocdisp'])){
    $config_enablepostprocdisp = $_POST['enablepostprocdisp'];
}
if(isset($_GET['reportName'])){
        $reportName = $_GET['reportName'];
}
if(isset($_GET['category'])) {
	$category = $_GET['category'];
}
if(isset($_GET['reportid'])) {
  //get the content of the URL parameter
  $newzbinreportID = $_GET['reportid'];
  //check if the content looks like a URL
  if(preg_match('/http\:\/\//',$newzbinreportID)){
    //if the content looks like a URL, let's try to parse out the reportID
    preg_match('/\/post\/([0-9]+)\//',$newzbinreportID,$matches);
    $newzbinreportID = $matches[1];
  }
}
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<HEAD>
     <?php standardHead("NZBGet Micro App"); ?>
</HEAD>

<BODY>
<?php internetSecurity(); ?>
<div style="visibility:hidden;display:none;" id="progress"><div id="progress_bg"></div><a name="loading" /><div id="progress_box"><img id="progress_image" style="padding-left:5px;padding-top:5px;" src="images/ajax-loader.gif" alt="loading...">Your request is being processed...</div></div>
<div class="headercontent">
  <?php headerContent(); ?>
</div>
<div class="maincontent">
  <?php
    if(!is_dir($config_NZBDropPath)) {
      echo "<div class='warningmessage'>The NZB Drop Path directory does not appear to exist. Check your <a href='configuration.php'>configuration</a></div>";
    }
    if($config_enablenzbget == "enable"){
        if(isset($config_NZBgetAppPath) && isset($config_NZBgetConfigPath)){
          if(!is_file($config_NZBgetAppPath)) {
              echo "<div class='warningmessage'>The NZBGet Application directory does not appear to exist. Check your <a href='configuration.php'>configuration</a></div>";
              }
          if(!is_file($config_NZBgetConfigPath)){
              echo "<div class='warningmessage'>The NZBGet Configuration directory does not appear to exist. Check your <a href='configuration.php'>configuration</a></div>";
              }
        }
    }
  ?>
  <div class="block">
    <h2>NZBget MicroApp</h2>
    <?php
    if($config_enablenzbget != "enable"){
      die("<div class='infomessage'>NZBget is currently disabled. You can enable it in the <a href='configuration.php'>configuration</a> page.</div>");
    }
    //if there is an action set, let's do something with it. This is usually pause/unpause.
    if(isset($action)){
        switch ($action) {
            case "pauseD":
                unset($output);
                exec("$config_NZBgetAppPath -P D -c $config_NZBgetConfigPath", $output);
                break;
            case "unpauseD":
                unset($output);
                exec("$config_NZBgetAppPath -U D -c $config_NZBgetConfigPath", $output); 
                break;
            case "pausePP":
                unset($output);
                exec("$config_NZBgetAppPath -P O -c $config_NZBgetConfigPath", $output); 
                break;
            case "unpausePP":
                unset($output);
                exec("$config_NZBgetAppPath -U O -c $config_NZBgetConfigPath", $output); 
                break;
            case "scan":
                unset($output);
                exec("$config_NZBgetAppPath -S -c $config_NZBgetConfigPath", $output); 
                break;
            case "enableautorefresh":
                unset($output);
                $cfg->setValue("NZBget","nzbgetautorefresh", "enable");
                if($cfg->save()) { $output[1] = "Auto Refresh has been enabled."; }
                elseif($cfg->save() == false) { $output[1] = "<div class='warningmessage'>Configuration file could not be written to. Check the file/folder permissions.</div>"; }
                $config_nzbgetautorefresh = $cfg->get("NZBget","nzbgetautorefresh");
                break;
            case "disableautorefresh":
                unset($output);
                $cfg->setValue("NZBget","nzbgetautorefresh", "disable");
                if($cfg->save()) { $output[1] = "Auto Refresh has been disabled."; }
                elseif($cfg->save() == false) { $output[1] = "<div class='warningmessage'>Configuration file could not be written to. Check the file/folder permissions.</div>"; }
                $config_nzbgetautorefresh = $cfg->get("NZBget","nzbgetautorefresh");
                break;
            case "":
                unset($output);
                $output[1] = "No action was requested";
                break;
            default:
                unset($output);
                $output[1] = "The requested action ($action) could not be understood.";
        }
        echo "<div class='infomessage'>".str_replace('server returned: ','',$output[1])."</div>";
    }
    //Enable / Disable Auto-refresh
    if($config_nzbgetautorefresh =="enable"){ 
        echo "<a href='?action=disableautorefresh'>Disable Auto-Refresh</a>"." | ";
        //set the autorefresh
        echo "<meta http-equiv='refresh' content='30;url=nzbget.php'>";
    }
    elseif($config_nzbgetautorefresh =="disable"){ echo "<a href='?action=enableautorefresh'>Enable Auto-Refresh</a>"." | "; }
        
    echo "<a href='nzbget.php'>Refresh</a> | ";
    echo "<a href='?action=scan'>Scan Now</a> <br />";
    /********************************************\
     *        Functions to modify group         *
    \********************************************/
    //if an action was requested, let's perform the action and output to the screen
    if(isset($_GET['dlaction']) || isset($_GET['ppaction'])){
        //get the action
        if(isset($_GET['dlaction'])){
            $action = $_GET['dlaction'];
            $atype = "G";
        }elseif(isset($_GET['ppaction'])){
            $action = $_GET['ppaction'];
            $atype = "O";
        }
        //if the the did isn't set, let the user know
        if(isset($_GET['did']) || isset($_GET['ppid'])){
            if(isset($_GET['did'])){
                //get the did variable
                $id = $_GET['did'];
            }elseif(isset($_GET['ppid'])){
                //get the did variable
                $id = $_GET['ppid'];
            }
        }else{
            echo "<div class='infomessage'>A fileid from the group must be set.</div>";
        }
        switch($action) {
            case "top":
                $a = "T"; #- move group to the top of download queue;
                break;
            case "bottom":
                $a = "B"; #- move group to the bottom of download queue;
                break;
            case "down":
                $a = "+1"; # - move group down in download queue to <offset>;
                break;
            case "up":
                $a = "-1"; # - move group up in download queue to <offset>;
                break;
            case "pause":
                $a = "P"; # - pause group;
                break;
            case "resume":
                $a = "U"; # - unpause (resume) group;
                break;
            case "delete":
                $a = "D"; # - delete group from download queue;
                break;
            default:
                echo "<div class='infomessage'>The requested action could not interpreted.</div>";
                $a = "fail";
        }
        if($a != "fail") {
            //unset the input
            unset($output);
            $command = "$config_NZBgetAppPath -E $atype $a $id -c $config_NZBgetConfigPath";
            exec($command, $output);
            unset($output[0]);
            $output[1] = str_replace("server returned: ","",$output[1]);
            echo "<div class='infomessage'>".$output[1]."</div>";
            //print_r($output);
        } 
    } 
    /********************************************\
     *          Functions to get Info           *
    \********************************************/
    //clear the array
    unset($output);
    //get the array of groups (NZBs) that are queued (includes junk text)
    exec("$config_NZBgetAppPath -L G -c $config_NZBgetConfigPath", $output);
    unset($output[0]);
    //take the groups and text and put it into a string
    $output = implode("\n",$output);
    //break out just the lines we need (groups)
    preg_match('/-----------------------------------\n([^>]+)\n-----------------------------------\n([^>]+)/m',$output,$matches);
    $status_msg = $matches[2];
    /********************************************\
     *         NZBget Current Downloads         *
    \********************************************/
    echo "<h3>Current Downloads</h3>";
    //Pause and Unpause commands for downloads
    echo "<a href='?action=pauseD'>Pause</a>";
    echo " | ";
    echo "<a href='?action=unpauseD'>Unpause</a>";
    //if($config_enablenzbgetrate == "enable") {
    echo " | ";
    echo "Rate: <form style='display: inline;' action='nzbget.php' method='get'><input type='text' name='nzbgetrate' id='nzbgetrate' style='width: 30px;'><input type='submit' value='Set'></form>";
    if(isset($_GET['nzbgetrate'])) { 
        //set the rate
        unset($output);
        //get the array of groups (NZBs) that are queued (includes junk text)
        exec("$config_NZBgetAppPath -R ".$_GET['nzbgetrate']." -c $config_NZBgetConfigPath", $output);
        unset($output[0]);
        //let the user know the output
        echo "<div class='infomessage'>".str_replace("server returned:","",$output[1])."</div>";
    }
    //}
    echo "<br />";
    //put just want we need back into an array
    $dlcontent = explode("\n",$matches[1]);
    unset($matches);
    unset($output);
    //loop through the array and clean it up and output it
    //when there is noting here, we shouldn't display the options.
    //if($dlcontent[0]==""){
        $i = 0;
        foreach($dlcontent as $line) {
            echo "<div class='dlline'>";
            //Assign the last second part of the ID (final file) into a variable [pt1-pt2] otherjunk
            preg_match('/\[[0-9]+\-([0-9]+)\](.+)?\(([0-9]+) files?,([^\+]+)?\+?([^\+]+)?\)$/',$line,$matches);
            //Grab the high part of the group download id
            $did = $matches[1];
            //Grab the download (group) name
            $dname = $matches[2];
            //Grab the download info (eg. filesize, etc)
            $dinfofiles = $matches[3];
            $dinfosize = $matches[4];
            $dinfopaused = $matches[5];
            //if we don't have content, don't display the below
            if(!is_null($did)){ // && trim($dinfosize) != "0 B"
                echo "<a href='?dlaction=up&did=$did'><img src='images/bullet_arrow_up.png'></a><a href='?dlaction=down&did=$did'><img src='images/bullet_arrow_down.png'></a><a href='?dlaction=top&did=$did'><img src='images/bullet_arrow_top.png'></a><a href='?dlaction=bottom&did=$did'><img src='images/bullet_arrow_bottom.png'></a><a href='?dlaction=pause&did=$did'><img src='images/control_pause.png'></a><a href='?dlaction=resume&did=$did'><img src='images/control_play.png'></a><a href='?dlaction=delete&did=$did'><img src='images/delete.png'></a>";
                echo "<div class='dltitle'>".$dname."</div>";
                //echo "<div class='dlinfo'>".$dinfo."</div>";
                if($config_nzbgetDLdetails == "enable"){
                    echo "<div class='dlinfo'>";
                    echo " | Remaining: $dinfofiles files";
                    if(isset($dinfosize)){ echo ", $dinfosize";}
                    if(isset($dinfopaused)){ echo ", $dinfopaused";}
                    echo "</div>";
                }
                $i++;
            }//else{ echo "No files in queue.<br />"; }
            echo "</div>";
        }
        if($i == 0){ echo "No files in queue.<br />"; }
    //}else{ echo "No files in queue."; }
    /********************************************\
     *              NZBget History              *
    \********************************************/
    if($config_enablehistorydisp == "enable"){
        echo "<h3>History</h3>";
        unset($output);
        exec("$config_NZBgetAppPath -L H -c $config_NZBgetConfigPath", $output);
        //remove the unwanted lines
        unset($output[0]);
        //output all the lines with HTML breaks
        foreach($output as $line){
          echo $line;
          echo "<br />";
        }
    }
    /********************************************\
     *          NZBget PostProcessing           *
    \********************************************/

    if($config_enablepostprocdisp == "enable"){
        echo "<h3>Post Processing</h3>";
        echo "<a href='?action=pausePP'>Pause</a> | <a href='?action=unpausePP'>Unpause</a><br />";
        //Functions to get the PostProcessing Information split up
        //clear the array
        unset($output);
        //get the array of groups (NZBs) that are queued (includes junk text)
        exec("$config_NZBgetAppPath -L O -c $config_NZBgetConfigPath", $output);
        //remove the app return line
        unset($output[0]);
        //remove the line that tells us this is a post processing output
        unset($output[1]);
        //take the groups and text and put it into a string
        $output = implode("\n",$output);
        //break out just the lines we need (processing lines)
        preg_match('/-----------------------------------\n([^>]+)\n-----------------------------------/m',$output,$matches);
        $postproc_content = $matches[1];
        //clear the original array so we can re-use it
        unset($output);
        //put each line (processing) into the array
        $output = explode("\n",$matches[1]);
        unset($matches);
        //Then display the post processing information
        foreach($output as $line){
          //echo $line."<br />";
          preg_match('/\[([0-9]+)\]([^,\/]+)\/?([^,]+)?,?([^>]+)?/',$line,$matches);
          $ppid = $matches[1];
          $ppgname = $matches[2];
          $ppfname = $matches[3];
          $ppmsg = $matches[4];
          //echo "PPID: $ppid | Group: $ppgname | File Name: $ppfname | Message: $ppmsg <br />";
          if(!is_null($ppid)){
                echo "<div class='ppline'>";
                if(isset($ppmsg)){
                    echo "<div class='ppinfo'>";
                    //echo "<img src='images/lightning.png'/>";
                    echo "Processing... &nbsp;";
                    //echo trim($ppmsg); // this is the message that indicates the item is being processed
                    echo "</div>";
                    echo "</a><a href='?ppaction=delete&ppid=$ppid'><img src='images/delete.png'></a>";
                    echo "<div class='dltitle'>".$ppgname."</div>";
                }else {
                    echo "<a href='?ppaction=up&ppid=$ppid'><img src='images/bullet_arrow_up.png'></a><a href='?ppaction=down&ppid=$ppid'><img src='images/bullet_arrow_down.png'></a><a href='?ppaction=top&ppid=$ppid'><img src='images/bullet_arrow_top.png'></a><a href='?ppaction=bottom&ppid=$ppid'><img src='images/bullet_arrow_bottom.png'></a></a><a href='?ppaction=delete&ppid=$ppid'><img src='images/delete.png'></a>";
                    echo "<div class='dltitle'>".$ppgname."</div>";
                }
                echo "</div>";
            }else{ echo "No files in queue."; }
          //echo $line;
          echo "<br />";
        }
    }
    /********************************************\
     *              NZBget Status               *
    \********************************************/
    echo "<h3>Status</h3>";
    //if we aren't downloading anything, let's use the basic status message
    if(is_null($status_msg)) {
      unset($output);
      exec("$config_NZBgetAppPath -L S -c $config_NZBgetConfigPath", $output);
      //Removing: Request sent
        unset($output[0]);
      //Removing: Remaining size: 0.00 MB
        unset($output[1]);
      //Removing: Current download rate: 0.0 KB/s
        unset($output[2]);
      //Removing: Threads running: #
        unset($output[7]);
      //Loop through the remaining array and output the text  
      foreach($output as $line){
        echo $line;
        echo "<br />";
      }    
    }else{
      echo str_replace("\n","<br />",$status_msg);
      echo "<br />";
    }
    // Get the disk size
    echo "<br />";
	//added the check to see if /share/ exists as a directory -- needs to be fixed for portability
    if(is_dir('/share/')){
		$disk_pct = disk_free_space("/share/") / disk_total_space("/share/");    
		$size = disk_free_space("/share/");
		
		echo "Disk Pct Remaining: ".round(($disk_pct*100),2)."%<br />";
		$i=0;
		$iec = array("B", "Kb", "MB", "GB", "TB");
		while (($size/1024)>1) {
			$size=$size/1024;
			$i++;}
		echo "Disk Space Remaining: ".round($size,1)." ".$iec[$i];
		if($_SERVER['REMOTE_ADDR'] != "127.0.0.1"){ //don't show the filespace bar when browsing directly from the PCH
			echo "<br /><div class='dsk_used' style='width:".round(((1-$disk_pct)*100),2)."px;'></div><div class='dsk_free' style='width:".round(($disk_pct*100),2)."px;'></div><br />";
		}
	}
	else{
		echo "<div class='infomessage' style='display:none;'>We had some trouble getting the disk space... the disk space check is currently hardcoded with the /share/ folder that is typically found on the popcornhour.</div>";
	}	

    /********************************************\
     *            Add Files / URL               *
    \********************************************/
    echo "<h3>Add Files</h3>";
    if($_SERVER['REMOTE_ADDR'] != "127.0.0.1"){ //don't show the upload NZB form when browsing directly from the PCH
        echo "<form enctype='multipart/form-data' action='nzbget.php' method='POST'>
              <input type='hidden' name='MAX_FILE_SIZE' value='10000000' />
              <div class='fielddesc'>Upload NZB: </div><input name='uploadedfile' type='file' />
              <input type='submit' value='Upload' onclick='return loadSubmit()'/>
              </form>
              ";
        if($_FILES != NULL){
            // In PHP versions earlier than 4.1.0, $HTTP_POST_FILES should be used instead
            // of $_FILES.
            if(basename($_FILES['uploadedfile']['name']) != ""){
                $uploadfile = $config_NZBDropPath."/".basename($_FILES['uploadedfile']['name']);
            }else {
                $uploadfile = $config_NZBDropPath."/".$_FILES['uploadedfile']['name'];
            }
            //echo "Upload file is: $uploadfile <br />";
            if (move_uploaded_file($_FILES['uploadedfile']['tmp_name'], $uploadfile)) {
                echo "<div class='infomessage'>File was successfully uploaded.</div>";
            } else {
                echo "<div class='warningmessage'>The file upload was unsuccessful. Make you you selected a valid file.</div>";
                //echo '<br />Here is some more debugging info:';
                //print_r($_FILES);
            }
        }
    }
    // **
    // ** Get the Newzbin Report or regular NZB
    // **
      ?>
      <form action="nzbget.php" method="get">
      <div class="fielddesc">Add Newzbin URL/Report:</div><input type="text" name="reportid" size='15' value="<?php if(isset($_GET['reportid'])) { echo $_GET['reportid']; } ?>"/><input type="submit" value="Download Now" onclick="return loadSubmit()"/>
      </form>
      <?php 
      //If there is something in that variable, let's do something with it
      if(isset($newzbinreportID)) { 
        if($newzbinreportID == "") {
          die("<div class='warningmessage'>You didn't enter a Report ID or URL...</div>");
        }
      }
	  
      //if we got here, then the report isn't NULL, so let's perform the action
      if(($action == "reporttest" || $action="reportactual") && $newzbinreportID != NULL) {
        /*------------------------------*\
	     |  Get NZBmatrix NZB by Report |
	    \*------------------------------*/
		//temporary solution to get NZBMatrix downloads working -- the overall download code will need to be refactored
		if(isset($_GET['indexer'])){if(strtolower($_GET['indexer']) == "nzbmatrix"){
			//Alternative method for categories (coming directly from search)
			preg_match('/(CATEGORY\:)?([^ >]+)( > .*)?/i', $category, $category);
			$category = $category[2];

			//build the url
			$url = 'http://nzbmatrix.com/api-nzb-download.php?id='.$newzbinreportID.'&username='.$config_nzbmatrixuname.'&apikey='.$config_nzbmatrixapikey;
			//get the contents
			$content = file_get_contents($url);
			if(isset($reportName)){ $nzbfilename = $reportName; } //***probably need to come back and look at this (strip bad characters)
			else{ $nzbfilename = "nzbmatrix_".$newzbinreportID; }
			
			if($config_sabnzbdnaming_enable == 'enable'){
				/* --- Category Style Naming --- */
				//save to the drop path
				//Check to see if the category folder exists
				if(file_exists($config_NZBDropPath . "/" . $category . "/")){
					//if the category folder exists, let's save the file there
					$nzbfilename = $config_NZBDropPath . "/" . $category . "/" . $nzbfilename . ".nzb"; 
				}else{
					//otherwise let's try to create the folder
					if(mkdir($config_NZBDropPath . "/" . $category)){
						echo "Created the directory ".$config_NZBDropPath . "/" . $category." <br />";
						//make sure the permissions are set so other users on the system can use the folder we created
						chmod($config_NZBDropPath . "/" . $category, 0777);
						//----->I would like to put some chown chgrp stuff in here, but I would need to know everyone's user
						//if we can create the folder, let's save it there
						$nzbfilename = $config_NZBDropPath . "/" . $category . "/" . $nzbfilename . ".nzb"; 						
					}else{
						//if that fails, let's save it in the normal location using the sabnzbd style category in the name
						$nzbfilename = $config_NZBDropPath . "/{{" . $category . "}}" . $nzbfilename . ".nzb"; 
					}
				}
			}else{
				/* --- Regular Style Naming --- */
				//If the user doesn't want SAB category support, let's use basic naming without category support
				$nzbfilename = $config_NZBDropPath . "/" . $nzbfilename . ".nzb"; 
			}
			//echo "I'm going to write to the file: $nzbfilename <br />";
			$fh = fopen($nzbfilename, 'w'); // or die("can't open file $nzbfilename <br />");
			if($fh != FALSE) {
				echo "Writing to file $nzbfilename <br />";
				if(fwrite($fh, $content) != FALSE){ //or die("can't write to file $nzbfilename <br />");
					//successfully wrote NZB
					echo "<div class='infomessage'>Successfully downloaded and wrote NZB as $nzbfilename</div>";
				} else { echo "<div class='warningmessage'>Can't write to file $nzbfilename </div>"; }
				fclose($fh);
			} else { echo "<div class='warningmessage'>Couldn't open file $nzbfilename </div>"; }
		}}
		else{
		/*----------------------------*\
	     |  Get Newzbin NZB by Report |
	    \*----------------------------*/
		//use the new post-request code to pull back the reports
        // submit these variables to the server:
        $data = array(
            'username' => $config_newzuname,
            'password' => $config_newzpw,
            'reportid' => $newzbinreportID
        );
         
        // send a request
        list($header, $content) = PostRequest(
            "http://www.newzbin.com/api/dnzb/",
            "http://popcornhour/NewzBook_web/index.php",
            $data
        );
        
        // parse out the header and get each line
        $HeaderLines = explode("\n", $header);
        // for each line, lets format the data we get from Newzbin
        foreach($HeaderLines as $CurrLine) {
            //make sure it's a line with a variable
            preg_match('/([^:]+): (.+)/',$CurrLine,$HdrLineContent);         
            //if the variables are set clean and assign them
            if(isset($HdrLineContent[1]) && isset($HdrLineContent[2])) {
                //remove dash from header
                $HdrLineContent[1] = str_replace("-","_",$HdrLineContent[1]);
                //assign content to variable name
                ${$HdrLineContent[1]} = $HdrLineContent[2];
            }
        }

        if($X_DNZB_RCode == 200) {
            //generate the file
            if($action == "reportactual" && $newzbinreportID != NULL) {
                echo "<div class='infomessage'>";
                //create arrays
                $dirty2dash = array("/");
                $nzbfilename = str_replace($dirty2dash,"-",trim($X_DNZB_Name));
                $dirty2remove = array(":");
                $nzbfilename = str_replace($dirty2remove,"",$nzbfilename);
                
				
				if($config_sabnzbdnaming_enable == 'enable'){
					/* --- Category Style Naming --- */
					//save to the drop path
					//Check to see if the category folder exists
					if(file_exists($config_NZBDropPath . "/" . $category . "/")){
						//if the category folder exists, let's save the file there
						$nzbfilename = $config_NZBDropPath . "/" . $category . "/" . $nzbfilename . ".nzb"; 
					}else{
						//otherwise let's try to create the folder
						if(mkdir($config_NZBDropPath . "/" . $category)){
							echo "Created the directory ".$config_NZBDropPath . "/" . $category." <br />";
							//make sure the permissions are set so other users on the system can use the folder we created
							chmod($config_NZBDropPath . "/" . $category, 0777);
							//----->I would like to put some chown chgrp stuff in here, but I would need to know everyone's user
							//if we can create the folder, let's save it there
							$nzbfilename = $config_NZBDropPath . "/" . $category . "/" . $nzbfilename . ".nzb"; 						
						}else{
							//if that fails, let's save it in the normal location using the sabnzbd style category in the name
							$nzbfilename = $config_NZBDropPath . "/{{" . $category . "}}" . $nzbfilename . ".nzb"; 
						}
					}
				}else{
					/* --- Regular Style Naming --- */
					//If the user doesn't want SAB category support, let's use basic naming without category support
					$nzbfilename = $config_NZBDropPath . "/" . $nzbfilename . ".nzb"; 
				}
                
				
				//echo "I'm going to write to the file: $nzbfilename <br />";
                $fh = fopen($nzbfilename, 'w'); // or die("can't open file $nzbfilename <br />");
                if($fh != FALSE) {
                    echo "Writing to file $nzbfilename <br />";
                    if(fwrite($fh, $content) != FALSE){ //or die("can't write to file $nzbfilename <br />");
                        //We successfully wrote the NZB, lets remove it from the bookmarks if the user wants
                        if($config_deleteupondl == "delon"){
                            $data = array(
                                'username' => $config_newzuname,
                                'password' => $config_newzpw,
                                'action' => 'delete',
                                'reportids' => $newzbinreportID
                            );
                             
                            // send a request
                            list($deleteheader, $deletecontent) = PostRequest(
                                "http://www.newzbin.com/api/bookmarks/",
                                "http://popcornhour/NewzBook_web/index.php",
                                $data
                            );
                            echo "Removing reportID $SplitContent[0] from newzbin bookmarks<br />";
                        } else { echo "Delete option is turned off. Report $SplitContent[0] will stay in your bookmarks<br />"; }
                    } else { echo "<div class='warningmessage'>Can't write to file $nzbfilename </div>"; }
                    fclose($fh);
                } else { echo "<div class='warningmessage'>Couldn't open file $nzbfilename </div>"; }
                echo "Current Memory: ".memory_get_usage()." | Peak Memory: ".memory_get_peak_usage()."\n";
                echo "</div><br />";
                //exit;
            }
        }
        else { 
            echo "<div class='warningmessage'>Error with response code: $X_DNZB_RCode <br />"; 
            ECHO "Error Message: $X_DNZB_RText</div>";
        }
       }
	  } 
    ?>
  </div>
</div>
</BODY>
